﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsMobile.Forms;
using System.Runtime.InteropServices;

namespace Weebing.Mobile
{
    public partial class MainForm : Form
    {
        [DllImport("coredll.dll", SetLastError = true)]
        public static extern IntPtr DestroyWindow(IntPtr hWnd);

        [DllImport("coredll.dll", SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        CameraCaptureDialog ccd = new CameraCaptureDialog();
        string windowTitle = "";

        public MainForm()
        {
            InitializeComponent();

            InitializeCamera();
            windowTitle = GetCameraCaptureDialogTitle(ccd);
        }

        private void InitializeCamera()
        {
            ccd.Owner = this;
            ccd.Resolution = new Size(480, 640);
            ccd.VideoTimeLimit = new TimeSpan(0, 0, 2);
            ccd.Mode = Microsoft.WindowsMobile.Forms.CameraCaptureMode.Still;
            ccd.StillQuality = Microsoft.WindowsMobile.Forms.CameraCaptureStillQuality.Normal;
            ccd.Title = "Take Picture Now";

            ccd.ShowDialog();

            if (DialogResult.OK == ccd.ShowDialog())
            {
                System.IO.File.Move(ccd.FileName, "My Documents\\img.jpg");
                this.Close();
                Application.Exit();
            }
            ccd.Dispose();

            IntPtr ptr = FindWindow(windowTitle);
            if (ptr != IntPtr.Zero)
            {
                DestroyWindow(ptr);
            }
        }

        private string GetCameraCaptureDialogTitle(Microsoft.WindowsMobile.Forms.CameraCaptureDialog dlg)
        {
            if (dlg.Mode == CameraCaptureMode.Still)
            {
                return string.Format("{0} [{1}]", ccd.Title, "Photo");
            }
            else
            {
                return string.Format("{0} [{1}]", ccd.Title, "Video");
            }
        }

        public static IntPtr FindWindow(string windowTitle)
        {
            return FindWindow(null, windowTitle);
        }
    }
}